import Taro, { RequestParams } from '@tarojs/taro'
import { responseSuccessFun, responseFailFun } from './interceptor'

// 创建一个请求函数
function createRequest<T extends RequestParams>(config: T): Promise<Request.RequestResult> {
  return new Promise((resolve, reject) => {
    const { url, method, data, header, noShowLoading, noShowDefaultError } = config
    const contentType = {
      'Content-Type': 'application/x-www-form-urlencoded' // 默认值
    }

    const _header = { ...contentType, ...header }
    !noShowLoading && Taro.showLoading({ title: '加载中...' })

    Taro.request({
      url,
      method,
      data,
      header: _header,
      success(res) {
        resolve(responseSuccessFun(res, noShowDefaultError))
      },
      fail: function (err) {
        reject(responseFailFun(err))
      }
    })
  })
}

export default createRequest
